<?php

/**
 * @author Jeevan Tomson
 * @copyright 2011
 */
require_once("FormValidator.php");

class UserManager {
    private $db;
    private $logger;
    
    public static $tablename = "tbl_users";
    public static $fields = array(); 

	public function __construct() {
		global $db;
		$this->objDBM = $db;
        $this->logger = Logger::getLogger(__CLASS__);
        
        if( count(UserManager::$fields) == 0 ) {
            UserManager::$fields = $this->objDBM->getFields(UserManager::$tablename);
        }
	}

	public function isUserExist( $username ) {
		try {
			$sql  = "SELECT count(*) as CNT FROM tbl_users WHERE username = '".$username."'";
			$result = $this->objDBM->excuteQuery($sql);			
			$row = mysql_fetch_assoc($result);
			$intCnt = $row["CNT"];
			if($intCnt == 0)
				return false;
			else
				return true;
		} catch(Exception $e) {
                $this->logger->error('Error in isUserExist: ' .$e->getMessage());
		}
	}
    
    public function getUser($userid) {
		try {
			$sql  = "SELECT * FROM tbl_users WHERE userid = '".$userid."'";
			$result = $this->objDBM->excuteQuery($sql);
			$row = mysql_fetch_assoc($result);
            applyStripSlashes($row);            
			return $row;
		} catch(Exception $e) {
                $this->logger->error('Error in getUser: ' .$e->getMessage());
		}
	}
    
    public function updateAccountInfo( $userid, $mobile, $email, $address ) {
        $op_result = new DBOpResult();
        $frmVldtr = new FormValidator();
        $error_msgs = $frmVldtr->validateAccUpdateData($userid, $mobile, $email, $address);
        
        if( count($error_msgs) > 0 ) {
            $op_result->Status = DB_OP_FAILED_STATUS;
            $op_result->Message = $error_msgs;    
        } else {
            try {
    			$sql  = "UPDATE tbl_users SET  ";
                $sql .= "mobile = '".$mobile."', ";
                $sql .= "email = '".$email."', ";
    			$sql .= "address = '".$address."' ";
                $sql .= "WHERE userid = '".$userid."'";
    			//echo $sql;
    			$resp = $this->objDBM->excuteQuery($sql);
                if($resp) {
                    $op_result->Status = DB_OP_SUCCESS_STATUS;
                    $op_result->AffectedRows = mysql_affected_rows();
                    $op_result->Message = "Account updated successfully.";    
                } else {
                    $op_result->Status = DB_OP_FAILED_STATUS;
                    $op_result->Message = "Update failed.";
                }
    		} catch(Exception $e) {
    			$this->logger->error('Error : ' .$e->getMessage());
    		}
        }
    	
        return $op_result;
    }
    
    public function updateUser( $userid, $name, $actype, $disabled = 0, $mobile, $email, $address, $comment = "" ) {
		$op_result = new DBOpResult();
        $frmVldtr = new FormValidator();
        
        $error_msgs = $frmVldtr->validateUpdateUserData($userid, $name, $actype, $disabled, $mobile, $email, $address, $comment);
		
		if( count($error_msgs) > 0 ) {
            $op_result->Status = DB_OP_FAILED_STATUS;
            $op_result->Message = $error_msgs;    
        } else {
            try {
    			$sql  = "UPDATE tbl_users SET  ";
                $sql .= "name = '".$name."', ";
                $sql .= "actype = '".$actype."', ";
                $sql .= "disabled = '".$disabled."', ";
                $sql .= "mobile = '".$mobile."', ";
                $sql .= "email = '".$email."', ";
    			$sql .= "address = '".$address."', ";
                $sql .= "comment = '".$comment."' ";
                $sql .= "WHERE userid = '".$userid."'";
    			//echo $sql;
    			$resp = $this->objDBM->excuteQuery($sql);
                if($resp) {
                    $op_result->Status = DB_OP_SUCCESS_STATUS;
                    $op_result->AffectedRows = mysql_affected_rows();
                    $op_result->Message = "User details updated successfully.";    
                } else {
                    $op_result->Status = DB_OP_FAILED_STATUS;
                    $op_result->Message = "Update failed.";
                }
    		} catch(Exception $e) {
    			$this->logger->error('Error : ' .$e->getMessage());
    		}
        }
    	
        return $op_result;
	}
    
    private function validateOldPassword($userid, $password) {
        $isValid = false;
        try {
			$sql  = "SELECT IF( (PASSWORD = PASSWORD( '".$password."' )), true, false ) as VALID FROM tbl_users WHERE userid = '".$userid."'";
			$result = $this->objDBM->excuteQuery($sql);
			$row = mysql_fetch_assoc($result);            
			if( $row["VALID"] ) {
                $isValid = true;
            }
		} catch(Exception $e) {
                $this->logger->error('Error in validateOldPassword: ' .$e->getMessage());
		}
        return $isValid;
    }
    
    public function checkUserNameAvailability($username) {
        $isAvailable = false;
        try {
			$sql  = "SELECT IF( COUNT( * ) >0, false, true ) AS AVAILABLE FROM tbl_users WHERE username  = '".$username."'";
			$result = $this->objDBM->excuteQuery($sql);
			$row = mysql_fetch_assoc($result);            
			if( $row["AVAILABLE"] ) {
                $isAvailable = true;
            }
		} catch(Exception $e) {
                $this->logger->error('Error in validateOldPassword: ' .$e->getMessage());
		}
        return $isAvailable;
    }
    
    public function changePassoword( $userid, $oldpassword, $newpassword, $confirmpassword ) {
        $op_result = new DBOpResult();
        $frmVldtr = new FormValidator();
        $error_msgs = $frmVldtr->validateChangePasswordData($userid, $oldpassword, $newpassword, $confirmpassword);
        
        if( count($error_msgs) > 0 ) {
            $op_result->Status = DB_OP_FAILED_STATUS;
            $op_result->Message = $error_msgs;    
        } else {
            $valid = $this->validateOldPassword($userid,$oldpassword);
            if($valid == 1){
                try {
        			$sql  = "UPDATE tbl_users SET  ";
                    $sql .= "password = PASSWORD('".$newpassword."'), ";
                    $sql .= "firstlogin = 0 ";
                    $sql .= "WHERE userid = '".$userid."' AND password = PASSWORD('".$oldpassword."')";
        			//echo $sql;exit;
        			$resp = $this->objDBM->excuteQuery($sql);
                    if($resp) {
                        $op_result->Status = DB_OP_SUCCESS_STATUS;
                        $op_result->AffectedRows = mysql_affected_rows();
                        $op_result->Message = "Password updated successfully.";    
                    } else {
                        $op_result->Status = DB_OP_FAILED_STATUS;
                        $op_result->Message = "Update failed.";
                    }
        		} catch(Exception $e) {
        			$this->logger->error('Error : ' .$e->getMessage());
        		}
            } else {
                $op_result->Status = DB_OP_FAILED_STATUS;
                $op_result->Message = "Old password is not correct.";
            }
        }
        
        return $op_result;
    }
    
    public function addUser( $createdby, $name, $actype, $username, $password, $mobile, $email, $address, $comment = "", $disabled = 0 ) {
		$op_result = new DBOpResult();
        $frmVldtr = new FormValidator();
        $error_msgs = $frmVldtr->validateAddUserData( $name, $actype, $username, $password, $mobile, $email, $address, $comment );
		
        //printObject($error_msgs);exit;
		if( count($error_msgs) > 0 ) {
            $op_result->Status = DB_OP_FAILED_STATUS;
            $op_result->Message = $error_msgs;    
        } else {
            $isAvailable = $this->checkUserNameAvailability($username);
            if($isAvailable == 1){
                try {
        			$sql  = "INSERT INTO tbl_users ( username, password, actype, disabled, ";  
                    $sql .= "name, mobile, email, address, comment ) VALUES ( ";
                    $sql .= "'".$username."', PASSWORD('".$password."'), '".$actype."', '".$disabled."', ";
                    $sql .= "'".$name."', '".$mobile."', '".$email."', '".$address."', '".$comment."' )";
        			//echo $sql;exit;
        			$resp = $this->objDBM->excuteQuery($sql);
                    if($resp) {
                        $op_result->Status = DB_OP_SUCCESS_STATUS;
                        $op_result->InsertId = mysql_insert_id();
                        $op_result->Message = "User added successfully.";    
                    } else {
                        $op_result->Status = DB_OP_FAILED_STATUS;
                        $op_result->Message = "Operation failed.";
                    }
        		} catch(Exception $e) {
        			$this->logger->error('Error : ' .$e->getMessage());
        		}
            } else {
                $op_result->Status = DB_OP_FAILED_STATUS;
                $op_result->Message = "User Name already taken.";
            }
        }
        
        return $op_result;
	}
    
    public function deleteUser( $userid ) {
        $op_result = new DBOpResult();
		try {
			$sql  = "DELETE FROM tbl_users WHERE userid = '".$userid."'";
			$resp = $this->objDBM->excuteQuery($sql);
            if($resp) {
                $op_result->Status = DB_OP_SUCCESS_STATUS;
                $op_result->AffectedRows = mysql_affected_rows();
                $op_result->Message = "User deleted successfully.";    
            } else {
                $op_result->Status = DB_OP_FAILED_STATUS;
                $op_result->Message = "Operation failed.";
            }
		} catch(Exception $e) {
			$this->logger->error('Error : ' .$e->getMessage());
		}
        return $op_result;
	}

	public function getUsersCount() {
		$sql  = "SELECT count(*) as CNT FROM tbl_users";
		$result = $this->objDBM->excuteQuery($sql);			
		$row = mysql_fetch_assoc($result);
		$intCnt = $row["CNT"];
		return $intCnt;
	}


	public function getUsersFilterCount( $compname, $catname, $contname1, $phone1, $contname2, $phone2, $address, $desc ) {
		$sql  = "SELECT  count(*) as CNT FROM tbl_users TCOMP LEFT JOIN tbcategory TCAT ";
		$sql .= "ON ( TCOMP.intCatId =  TCAT.intId ) ";
		if( $compname!="" || $catname!= "" || $contname1!= "" || $phone1!= "" || $contname2!= "" || $phone2!= "" || $address!= "" || $desc != "" ) {
			$sql .= "where ";
			$wherecond = "";
			if( $compname!= "" ) {
				$wherecond = "vchComanyName like '%".$compname."%' ";
			}
			if( $catname!= "" ) {
				if( $wherecond == "" ) $wherecond = "vchCategoryName like '%".$catname."%' ";
				else $wherecond .= "and vchCategoryName like '%".$catname."%' ";				
			}
			if( $contname1!= "" ) {
				if( $wherecond == "" ) $wherecond = "vchContactName1 like '%".$contname1."%' ";
				else $wherecond .= "and vchContactName1 like '%".$contname1."%' ";				
			}
			if( $phone1!= "" ) {
				if( $wherecond == "" ) $wherecond = "vchPhone1 like '%".$phone1."%' ";
				else $wherecond .= "and vchPhone1 like '%".$phone1."%' ";				
			}
			if( $contname2!= "" ) {
				if( $wherecond == "" ) $wherecond = "vchContactName2 like '%".$contname2."%' ";
				else $wherecond .= "and vchContactName2 like '%".$contname2."%' ";				
			}
			if( $phone2!= "" ) {
				if( $wherecond == "" ) $wherecond = "vchPhone2 like '%".$phone2."%' ";
				else $wherecond .= "and vchPhone2 like '%".$phone2."%' ";				
			}
			if( $address!= "" ) {
				if( $wherecond == "" ) $wherecond = "txtAddress like '%".$address."%' ";
				else $wherecond .= "and txtAddress like '%".$address."%' ";
			}
			if( $desc!= "" ) {
				if( $wherecond == "" ) $wherecond = "txtDesc like '%".$desc."%' ";
				else $wherecond .= "and txtDesc like '%".$desc."%' ";
			}
			$sql .= $wherecond;
		}
		$result = $this->objDBM->excuteQuery($sql);			
		$row = mysql_fetch_assoc($result);
		$intCnt = $row["CNT"];
		return $intCnt;
	}

	public function getUsers( $page, $size, $name = "", $actype = "", $disabled = "", $mobile = "", $email = "", $address = "", $comment = "" ) {
		$page = $page * $size;
		$sql  = "SELECT * FROM tbl_users ";
		if( $name!="" || $actype!= "" || $disabled!= "" || $mobile!= "" || $email!= "" || $address!= "" || $comment!= "" ) {
			$sql .= "where ";
			$wherecond = "";
			if( $name!= "" ) {
				$wherecond = "name like '%".$name."%' ";
			}
			if( $actype!= "" ) {
				if( $wherecond == "" ) $wherecond = "actype = '".$actype."' ";
				else $wherecond .= "and actype = '".$actype."' ";				
			}
			if( $disabled!= "" ) {
				if( $wherecond == "" ) $wherecond = "disabled = '".$disabled."' ";
				else $wherecond .= "and disabled = '".$disabled."' ";				
			}
			if( $mobile!= "" ) {
				if( $wherecond == "" ) $wherecond = "mobile like '%".$mobile."%' ";
				else $wherecond .= "and mobile like '%".$mobile."%' ";				
			}
			if( $email!= "" ) {
				if( $wherecond == "" ) $wherecond = "email like '%".$email."%' ";
				else $wherecond .= "and email like '%".$email."%' ";				
			}
			if( $address!= "" ) {
				if( $wherecond == "" ) $wherecond = "address like '%".$address."%' ";
				else $wherecond .= "and address like '%".$address."%' ";				
			}
			if( $comment!= "" ) {
				if( $wherecond == "" ) $wherecond = "comment like '%".$comment."%' ";
				else $wherecond .= "and comment like '%".$comment."%' ";
			}
            
			$sql .= $wherecond;
		}
		$sql .= "order by name asc ";
		if( isset($page) && isset($size) )
		$sql .= "LIMIT $page, $size";
		//echo $sql;
		$result = $this->objDBM->excuteQuery($sql);
		$userList = array();
		while( $row = mysql_fetch_assoc($result) )
		{
		    applyStripSlashes($row);  
			array_push($userList,$row);			
		}
		return $userList;
	}

	public function getUsersByIndex( $page, $size, $index="a" ) {
		$page = $page * $size;
		$sql  = "SELECT TCOMP.intId, TCOMP.vchComanyName, TCOMP.intCatId, TCAT.vchCategoryName, TCOMP.vchContactName1, TCOMP.vchPhone1, ";
		$sql .= "TCOMP.vchContactName2, TCOMP.vchPhone2, TCOMP.txtAddress, TCOMP.txtDesc, ";
		$sql .= "TCAT.txtCatDesc FROM tbl_users TCOMP LEFT JOIN tbcategory TCAT ";
		$sql .= "ON ( TCOMP.intCatId =  TCAT.intId ) ";
		if( $index!="" ) {
			$sql .= "where vchComanyName like '".$index."%' ";
		}
		$sql .= "order by TCOMP.vchComanyName asc ";
		if( isset($page) && isset($size) )
		$sql .= "LIMIT $page, $size";
		//echo $sql;
		$result = $this->objDBM->excuteQuery($sql);
		$companyList = array();
		while( $row = mysql_fetch_assoc($result) )
		{
			$company = array	(
				"id" =>  $row["intId"],
				"compname" => $row["vchComanyName"],
				"catId" =>  $row["intCatId"],
				"catname" => $row["vchCategoryName"],
				"contactname1" => $row["vchContactName1"],
				"phone1" => $row["vchPhone1"],
				"contactname2" => $row["vchContactName2"],
				"phone2" => $row["vchPhone2"],
				"address" => $row["txtAddress"],
				"compdesc" => $row["txtDesc"],
				"catdesc" => $row["txtCatDesc"]
			);
			array_push($companyList,$company);			
		}
		return $companyList;
	}

	public function getUsersByCatIndex( $page, $size, $index="a" ) {
		$page = $page * $size;
		$sql  = "SELECT TCOMP.intId, TCOMP.vchComanyName, TCOMP.intCatId, TCAT.vchCategoryName, TCOMP.vchContactName1, TCOMP.vchPhone1, ";
		$sql .= "TCOMP.vchContactName2, TCOMP.vchPhone2, TCOMP.txtAddress, TCOMP.txtDesc, ";
		$sql .= "TCAT.txtCatDesc FROM tbl_users TCOMP LEFT JOIN tbcategory TCAT ";
		$sql .= "ON ( TCOMP.intCatId =  TCAT.intId ) ";
		if( $index!="" ) {
			$sql .= "where vchCategoryName like '".$index."%' ";
		}
		$sql .= "order by TCAT.vchCategoryName asc, TCOMP.vchComanyName asc ";
		if( isset($page) && isset($size) )
		$sql .= "LIMIT $page, $size";
		//echo $sql;
		$result = $this->objDBM->excuteQuery($sql);
		$companyList = array();
		while( $row = mysql_fetch_assoc($result) )
		{
			$company = array	(
				"id" =>  $row["intId"],
				"compname" => $row["vchComanyName"],
				"catId" =>  $row["intCatId"],
				"catname" => $row["vchCategoryName"],
				"contactname1" => $row["vchContactName1"],
				"phone1" => $row["vchPhone1"],
				"contactname2" => $row["vchContactName2"],
				"phone2" => $row["vchPhone2"],
				"address" => $row["txtAddress"],
				"compdesc" => $row["txtDesc"],
				"catdesc" => $row["txtCatDesc"]
			);
			array_push($companyList,$company);			
		}
		return $companyList;
	}

	

	

	
}


?>